﻿using GlennQuigmire.API.Application.GDtos;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.XSSF.UserModel;

namespace GlennQuigmire.API.Application.Commands
{
    public class ExcelLeadIntoHander : IRequestHandler<ExcelLeadIntoCommand, FileExportDto>
    {


        private readonly IBaseRepositorys<InboundOrder> baseRepositorys;

        public ExcelLeadIntoHander(IBaseRepositorys<InboundOrder> baseRepositorys)
        {
            this.baseRepositorys = baseRepositorys;
        }

        /// <summary>
        /// 导出入库单excel文件
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<FileExportDto> Handle(ExcelLeadIntoCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportDto();
            var list = baseRepositorys.GetAll().ToList();
            Console.WriteLine(list.Count);
            var book=new XSSFWorkbook();
            var sheet = book.CreateSheet("入库单");
            var row = sheet.CreateRow(0);
            //设置表头的各个标题
            row.CreateCell(0).SetCellValue("入库单号");
            row.CreateCell(1).SetCellValue("入库日期");
            row.CreateCell(2).SetCellValue("备注");
            row.CreateCell(3).SetCellValue("创建时间");

            //初始化索引
            int i = 1;
            //遍历入库单列表
            foreach (var item in list)
            {
                row = sheet.CreateRow(i);
                row.CreateCell(0).SetCellValue(item.InboundOrderNumber);
                row.CreateCell(1).SetCellValue(item.InboundOrderDate.ToString("yyyy-MM-dd HH:mm:ss"));
                row.CreateCell(2).SetCellValue(item.Remark);
                row.CreateCell(3).SetCellValue(item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                i++;
            }

            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }
            string contextType = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string fileName = "入库单导出.xlsx";
            result.FileBytes = bytes;
            result.MimeType = contextType;
            result.FileName = fileName;
            return result;
        }
    }
}
